package jh.com.jhappbf.weight.collect;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.blankj.utilcode.util.TimeUtils;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.work.WorkSettingActivity;

/**
 * @author : wwh
 * e-mail  : 953889276@qq.com
 * time    : 2019-7-6 14:34:16
 * desc    :
 */
public class InnerCollectActivity extends AbActivity {

    private View mContentView;
    private View mErrorView;
    private Context mAppContext;
    private LinearLayout mHeaderLayout;
    private ListView mListView;
    private Button mTryAgain;
    private List<JSONObject> mData;
    private Button mTitleRightBtn;
    private List<String> mHeaderTitle;
    private Drawable mLeftDrawable;
    private int mColumnWidth;
    private AbLoadDialogFragment mDialogFragment = null;
    private CollectBaseAdapter mAdapter;
//    private CollectInputSettingModel mSettingModel;
    private final int GETSETTING = 0X0001;
    private String mFlag;
    private String mTypes;
    private HorizontalScrollView mScrollView;

    private String mStartTime = "";
    private String mStartDate = "";
    private String mEndTime = "";
    private String mEndDate = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.activity_inner_collect, null);
        mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);

        Intent i = getIntent();
        mFlag = i.getStringExtra("flag");
//        mSettingModel = i.getParcelableExtra("setting");

        AbTitleBar mAbTitleBar = this.getTitleBar();
        switch (mFlag) {
            case "sale":
                mAbTitleBar.setTitleText("出库汇总");
                break;
            case "buy":
                mTypes = "销售";
                mAbTitleBar.setTitleText("货名汇总");//销售
                break;
            case "out":
                mTypes = "采购";
                mAbTitleBar.setTitleText("收货、货名汇总");//采购
                break;
            default:
                mAbTitleBar.setTitleText("客户汇总");
                break;
        }

        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAbTitleBar.setLogoOnClickListener(v -> {
//            Intent i1 = new Intent();
//            i1.putExtra("result", mSettingModel);
//            setResult(RESULT_OK, i1);
            finish();
        });
        View rightViewMore = mInflater.inflate(R.layout.title_right_app_btn_view, null);
        mAbTitleBar.addRightView(rightViewMore);
        mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_btn);
        initView();
    }

    private void initView() {
        mAppContext = getApplicationContext();
        mHeaderLayout = mContentView.findViewById(R.id.collect_input_weight_title);
        mListView = mContentView.findViewById(R.id.collect_input_weight_listView);
        mScrollView = mContentView.findViewById(R.id.collect_weight_hscroll);
        mAdapter = new CollectBaseAdapter();
        mData = new ArrayList<>();
        //View footer=findViewById(R.layout.listview_footer);
        mListView.addFooterView(View.inflate(this, R.layout.listview_footer, null));
        mListView.setAdapter(mAdapter);
        mTryAgain = mErrorView.findViewById(R.id.network_error_btn);
//        mLayoutExport = mContentView.findViewById(R.id.collect_weight_export_excel_layout);
//        setExportPosition();
        mHeaderTitle = new ArrayList<>();
        mLeftDrawable = ContextCompat.getDrawable(this, R.mipmap.table_line);
        mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(), mLeftDrawable.getMinimumHeight());
        mColumnWidth = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 55, getResources().getDisplayMetrics());
        mTryAgain.setOnClickListener(v -> {
            setAbContentView(mContentView);
            refresh();
        });

        mTitleRightBtn.setOnClickListener(v -> {
            Intent i = new Intent(this, WorkSettingActivity.class);
            i.putExtra("flag", "input");
//            i.putExtra("setting", mSettingModel);
            startActivityForResult(i, GETSETTING);
        });

//        mLayoutExport.setOnClickListener(v -> {
//            String url = Constant.ServerPath + "outPutFile/collect/" + State.mAccount + mTypes + ".xls";
//            new ExportHelper(mDialogFragment, url, CollectWeigh.this, mTypes + "汇总").export();
//        });

        refresh();
    }

    ///刷新
    private void refresh() {
        mDialogFragment = AbDialogUtil.showLoadDialog(InnerCollectActivity.this, R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(this::getData);
    }


    // 获取数据
    private void getData() {
        String methodName = "collectWeight";
        switch (mFlag) {
            case "sale":
                methodName = "collectSale";
                break;
            case "buy":
                methodName = "collectBuy";//销售
                break;
            case "out":
                methodName = "collectOut";//采购
                break;
            default:
                break;
        }

        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("startTime");
        param.add("endTime");
        param.add("cargoname");
        param.add("receiver");
        param.add("sender");
        param.add("user");
        param.add("admin");

        if (mStartDate.isEmpty() || mStartTime.isEmpty()) {
            mStartDate = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
            mStartTime = "00:00:00";
        }

        if (mEndDate.isEmpty() || mEndTime.isEmpty()) {
            mEndDate = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
            mEndTime = "23:59:59";
        }
        value.add(mStartDate + " " + mStartTime);
        value.add(mEndDate + " " + mEndTime);
        value.add("");
        value.add("");
        value.add("");
        value.add(State.mAccount);
        value.add("inner");
        Listener<String> listener = response -> {
            Log.e("wwh", "onResponse: " + response);
            AbDialogUtil.removeDialog(this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null) {
                mHeaderTitle = new ArrayList<>();
                if (newListData.size() > 0) {
                    String[] head = newListData.get(0).optString("alias").split(",");
                    mHeaderTitle = Arrays.asList(head);
                    makeHead();
                }
                mData.clear();
                mData.addAll(newListData);
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            setAbContentView(mErrorView);
            mData.clear();
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            mStartDate = data.getStringExtra("startDate");
            mStartTime = data.getStringExtra("startTime");
            mEndDate = data.getStringExtra("endDate");
            mEndTime = data.getStringExtra("endTime");
            refresh();
        }
    }

    // 生成表头
    private void makeHead() {
        mHeaderLayout.removeAllViews();
        for (int index = 0; index < mHeaderTitle.size(); index++) {
            TextView txt = new TextView(this);
            switch (mHeaderTitle.get(index)) {
                case "发货单位":
                case "收货单位":
                    txt.setWidth(mColumnWidth * 3);
                    break;
                case "货名":
                    txt.setWidth(mColumnWidth * 2);
                    break;
                default:
                    txt.setWidth((int) (mColumnWidth * 1.5));
                    break;
            }

            txt.setTextColor(Color.BLACK);
            txt.setGravity(Gravity.CENTER);
            txt.setCompoundDrawables(mLeftDrawable, null, null, null);
            txt.setPadding(1, 1, 1, 1);
            txt.setId(index);
            txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            txt.setText(mHeaderTitle.get(index));
            mHeaderLayout.addView(txt);
        }
    }

    private class CollectBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TableLayout tableLayout;
            if (convertView == null) {
                tableLayout = new TableLayout(InnerCollectActivity.this);
                TableRow tableRow = new TableRow(InnerCollectActivity.this);
                Drawable mItemSelect = ContextCompat.getDrawable(InnerCollectActivity.this, R.drawable.list_item_bg);
                tableRow.setBackground(mItemSelect);
                tableRow.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
                for (int index = 0; index < mHeaderTitle.size(); index++) {
                    TextView txt = new TextView(InnerCollectActivity.this);
                    switch (mHeaderTitle.get(index)) {
                        case "发货单位":
                        case "收货单位":
                            txt.setWidth(mColumnWidth * 3);
                            break;
                        case "货名":
                            txt.setWidth(mColumnWidth * 2);
                            break;
                        default:
                            txt.setWidth((int) (mColumnWidth * 1.5));
                            break;
                    }

                    txt.setTextColor(Color.BLACK);
                    txt.setGravity(Gravity.CENTER);
                    txt.setCompoundDrawables(mLeftDrawable, null, null, null);
                    txt.setPadding(1, 0, 1, 0);
                    txt.setId(index);
                    txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    tableRow.addView(txt);
                }
                tableLayout.addView(tableRow);
                convertView = tableLayout;
                convertView.setTag(tableLayout);
            } else {
                tableLayout = (TableLayout) convertView.getTag();
            }

            JSONObject data = mData.get(position);
            String content;
            for (int index = 0; index < mHeaderTitle.size(); index++) {
                TextView txt = tableLayout.findViewById(index);
                if (txt == null) {
                    continue;
                }
                content = data.optString(mHeaderTitle.get(index));
                if ("null".equals(content)) {
                    content = "";
                }
                txt.setText(content);
            }
            return convertView;
        }
    }

    @Override
    public void onBackPressed() {

        finish();
    }
}
